package com.czy.owner.ui.store;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.RelativeLayout;

import com.czy.owner.R;
import com.czy.owner.adapter.NearStoreListAdapter;
import com.czy.owner.api.BindStoreApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.NearStoreListModel;
import com.czy.owner.entity.OwnerInfoModel;
import com.czy.owner.entity.StoreDataModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.widget.UniversalDialog;
import com.easemob.cases.MessageHelper;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.zxing.library.ZXingConstants;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2017/11/9.
 * 门店列表
 */

public class StoreListActivity extends BaseActivity {
    public static final int BIND_TYPE2 = 0x33;
    public static final int SEARCH_BIND_TYPE = 0x44;
    @BindView(R.id.rv_store_list)
    EasyRecyclerView rvStoreList;
    @BindView(R.id.rl_no_login_tip)
    RelativeLayout rlNoLoginTip;
    private List<NearStoreListModel> mNearlist = new ArrayList<>();
    private NearStoreListAdapter adapter;
    private OwnerInfoModel ownerInfoModel = null;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_near_store_list;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText("门店列表");
        if (UserHelper.getInstance().isLogined()) {
            rlNoLoginTip.setVisibility(View.GONE);
        } else {
            rlNoLoginTip.setVisibility(View.GONE);
        }
        ownerInfoModel = UserHelper.getInstance().getOwnerInfoModel(StoreListActivity.this);
        mNearlist = (List<NearStoreListModel>) getIntent().getSerializableExtra("nearList");
        MyLog.e("yang", "mNearlist==" + mNearlist.size());
        rvStoreList.setLayoutManager(new LinearLayoutManager(StoreListActivity.this));
        rvStoreList.setAdapterWithProgress(adapter = new NearStoreListAdapter(StoreListActivity.this));
        rvStoreList.addItemDecoration(new RecycleViewDivider(StoreListActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
        adapter.addAll(mNearlist);


        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<NearStoreListModel>() {
            @Override
            public void onItemClick(View view, int position, NearStoreListModel o) {
                Intent ti = new Intent(StoreListActivity.this, NoBindStoreDetailActivity.class);
                ti.putExtra("storeName", o.getStoreName());
                ti.putExtra("stroeLogo", o.getStroeLogo());
                ti.putExtra("description", o.getDescription());
                ti.putExtra("serviceNumber", o.getServiceNumber());
                ti.putExtra("storeLocation", o.getStoreLocation());
                ti.putExtra("gprsX", o.getGprsX());
                ti.putExtra("gprsY", o.getGprsY());
                ti.putExtra("storeId", o.getStoreId());
                ti.putExtra("banners", (Serializable) o.getResList());
                ti.putExtra("isScan", false);
                startActivityForResult(ti, BIND_TYPE2);

            }
        });
        adapter.setBindStoreListener(new NearStoreListAdapter.BindStoreListener() {
            @Override
            public void onBindClickListener(int storeId) {
                SharedPreferencesUtils.setParam(StoreListActivity.this, Constants.SHARED_PREFERENCES_KEY_IS_STORE_BIND_DIALOG, storeId);
                SharedPreferencesUtils.setParam(StoreListActivity.this, Constants.SHARED_PREFERENCES_KEY_IS_STORE_BIND, true);
                if (checkLoginState()) {
                    BindDialog(StoreListActivity.this.getString(R.string.bind_store_title), StoreListActivity.this.getString(R.string.sure_bind), StoreListActivity.this.getString(R.string.cancle_bind), storeId);
                }
            }
        });


    }

    @Override
    protected void updateViews() {

    }

    @OnClick({R.id.ll_search_store_name,R.id.tv_unbind_login})
    public void llSearchStoreName(View view) {
        switch (view.getId()){
            case R.id.ll_search_store_name:
                Intent ti = new Intent(StoreListActivity.this, StoreSearchActivity.class);
                startActivityForResult(ti, SEARCH_BIND_TYPE);
                break;
            case R.id.tv_unbind_login:
                SharedPreferencesUtils.setParam(StoreListActivity.this, Constants.SHARED_PREFERENCES_KEY_IS_STORE_BIND, true);
                if (checkLoginState()) {

                }
                break;
        }

    }




    private void BindDialog(String title, String sure, String cancle, final int storeId) {
        new UniversalDialog(StoreListActivity.this).builder().setTitle(title)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BindStoreRequest(storeId);
                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    private void BindStoreRequest(final int storeId) {
        ownerInfoModel = UserHelper.getInstance().getOwnerInfoModel(StoreListActivity.this);
        BindStoreApi bindStoreApi = new BindStoreApi(new HttpOnNextListener<StoreDataModel>() {
            @Override
            public void onNext(StoreDataModel model) {
                Gson gson = new GsonBuilder().create();
                String data = gson.toJson(model);
                UserHelper.getInstance().saveChainStores(StoreListActivity.this, data);
                MessageHelper.getInstance().reset();
                EMClient.getInstance().login(UserHelper.getInstance().getUserInfoModel(StoreListActivity.this).getImKey(), UserHelper.getInstance().getUserInfoModel(StoreListActivity.this).getImPasswd(), new EMCallBack() {//回调
                    @Override
                    public void onSuccess() {
                        MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(StoreListActivity.this.getApplicationContext()).getNickName(),
                                UserHelper.getInstance().getUserInfoModel(StoreListActivity.this.getApplicationContext()).getUserLogo());
                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();
                        MyLog.d("King", "登录聊天服务器成功！");
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }

                    @Override
                    public void onError(int code, String message) {
                        MyLog.d("King", "登录聊天服务器失败！" + code + "|" + message);
                    }
                });
                for (int i = 0; i <model.getChainStores().size(); i++) {
                    if(model.getChainStores().get(i).getStoreId()==storeId){
                        String storeName = model.getChainStores().get(i).getStoreName();
                        ownerInfoModel.setStoreName(storeName);
                        break;
                    }
                }
                ownerInfoModel.setStoreId(storeId);
                ownerInfoModel.setBindStoreId(storeId);
                UserHelper.getInstance().setOwnerInfoModel(StoreListActivity.this, ownerInfoModel);
                UserHelper.getInstance().setSelectStoreId(StoreListActivity.this, storeId);
                SharedPreferencesUtils.setParam(StoreListActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, storeId);
                PhoneUtils.ShowToastMessage(StoreListActivity.this, "绑定成功");
                SharedPreferencesUtils.remove(Constants.SHARED_PREFERENCES_KEY_IS_STORE_BIND);
                setResult(RESULT_OK);
                finish();


            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                PhoneUtils.ShowToastMessage(StoreListActivity.this, e.getMessage());
            }
        }, this);

        bindStoreApi.setSession(UserHelper.getInstance().getSessionInfoModel(StoreListActivity.this).getSession());
        bindStoreApi.setStoreId(storeId + "");
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(bindStoreApi);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case BIND_TYPE2:
                    setResult(RESULT_OK);
                    finish();
                    break;
                case SEARCH_BIND_TYPE:
                    setResult(RESULT_OK);
                    finish();
                    break;
            }
        }


    }
}
